<?php

namespace App\Http\Api\Controller\Common\Ai;

use App\Http\Api\CurrentUser;
use App\Service\Ai\ws\ChatWebSocketService;
use Exception;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\HttpServer\Annotation\Controller;

class ChatWebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{

    public function __construct(
        protected readonly ChatWebSocketService $service,
        protected readonly CurrentUser $currentUser
    )
    {
    }

    /**
     * 建立连接
     * @param $server
     * @param $request
     * @return void
     * @throws Exception
     */
    public function onOpen($server, $request): void
    {
        $this->service->bind($this->currentUser->getUser(), $request->fd);
    }


    /**
     * 接收消息
     * @param $server
     * @param $frame
     * @return void
     */
    public function onMessage($server, $frame): void
    {
        $this->service->handleMessage($frame);
    }


    /**
     * 关闭连接
     * @param $server
     * @param int $fd
     * @param int $reactorId
     * @return void
     */
    public function onClose($server, int $fd, int $reactorId): void
    {
        $this->service->unbind($fd);
    }


}